<template>
  <el-container>
    <!-- 固定在顶部的header -->

    <!-- 顶部标题 -->
    <el-header class="customHeader fixed-header">
      <div class="topBar"></div>
      <div class="headerContent">
        <!-- 左侧：Logo + 分隔线 + 标题 -->
        <div class="headerLeft">
          <img src="@/assets/image/logo.jpg" class="logo"  @click="$router.push('/')"/>
          <div class="headerDivider"></div>
          <div class="titleWrapper">
            <div class="mainTitle">讯航<span class="newsText">News</span></div>
            <div class="subTitle">——武大新闻整合平台</div>
          </div>
        </div>

        <div class="headerRightGroup">
          <!-- 右侧：搜索框 -->
          <div class="headerRight">
            <el-input
              v-model="searchText"
              placeholder="文章搜索"
              class="searchInput"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button class="custom-search-btn" @click="handleSearch">
                  <!-- 搜索逻辑待写 -->
                  <img src="@/assets/image/搜索.png" class="search-icon" alt="搜索" />
                </el-button>
              </template>
            </el-input>
          </div>
        </div>
      </div>
    </el-header>

    <!-- 添加占位元素避免内容被遮挡 -->
    <div class="header-placeholder"></div>

    <el-main>
      <!-- 第一部分：顶部图片 -->
      <!-- <div class="banner-image">
        <img src="../assets/image/R-C.jpg" alt="宣传横幅" style="width: 100%; height: 180px" />
      </div> -->

      <!-- 第二部分：顶部功能区 -->
      <div class="top-function-area">
        <div class="sortContent">
          <div class="sortButtons">
            <span class="sortLabel">排序：</span>
            <el-button
              type="primary"
              size="large"
              class="sortBtn sortTime"
              @click="handleSortByTime"
            >
            时间排序 {{ sortDirection === 'desc' ? '(升序)' : '(降序)' }}
            </el-button>

            <el-button
              type="primary"
              size="large"
              class="sortBtn sort-watch"
              @click="handleSortByWatch"
            >
              按浏览量排序
            </el-button>

            <span class="sortLabel">筛选：</span>
            <el-button type="primary" 
            size="large" 
            class="sortBtn sortHot" 
            @click="handleHotNews"
            :class="{ 'is-active': showHotNews }"
            >
              当前热门 {{ showHotNews ? '(已开启)' : '' }}
            </el-button>

            <div class="date-filter-group">
               <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                class="date-range-picker"
                :clearable="true"
                @clear="resetDateFilter"
              />
              <el-button
                type="primary"
                size="large"
                class="sortBtnbyDateRange fliterbyDateRange"
                @click="handlefliterbyDateRange"
                :disabled="!dateRange || dateRange.length !== 2"
              >
                按日期筛选
              </el-button>
              <el-button
                v-if="isDateFilterActive"
                type="danger"
                size="large"
                class="reset-date-filter"
                @click="resetDateFilter"
                >
                取消筛选
              </el-button>
            </div>
            <span class="sortLabel">抓取武大近期新闻：</span>
            <el-button type="primary" size="large" class="sortBtn whuNews" @click="handlewhuNews">
              从武大新闻网
            </el-button>

            <el-button type="primary" size="large" class="sortBtn wiseWhu" @click="handlewiseWhu">
              从智慧珞珈
            </el-button>

          </div>
          


          <hr />
        </div>
      </div>

      <!-- 第三部分：中间内容区 -->
      <div class="middle-content-area">
        <!-- 左侧20%：分类栏 -->
        <div class="category-sidebar">
            <div class="category-card">
                <el-menu  class="category-menu" @select="handleCategorySelect">
                <el-menu-item index="1">
                    <span class="category-item">武大咨询</span>
                </el-menu-item>
                <el-menu-item index="2">
                    <span class="category-item">珞珈人物</span>
                </el-menu-item>
                <el-menu-item index="3">
                    <span class="category-item">信息发布</span>
                </el-menu-item>
                <el-menu-item index="4">
                    <span class="category-item">校园生活</span>
                </el-menu-item>
                </el-menu>
            </div>
        </div>
        

        <!-- 右侧80%新闻卡片容器 -->
        <div class="newsContainer">
          <div class="newsCard" 
            v-for="(item, index) in paginatedNews"
            :key="index"
            @mouseenter="hoveredCardId = index" 
            @mouseleave="hoveredCardId = null"
            :class="{ 'selected-card': isBatchMode && selectedNews.has(index) }"
            @click="isBatchMode ? toggleSelect(index) : null"
          >

            <!-- 批量选择复选框 (只在批量模式显示) -->
            <div class="batch-checkbox" v-if="isBatchMode">
                <el-checkbox 
                :modelValue="selectedNews.has(index)"
                @click.stop
                @change="() => toggleSelect(index)"
                />
            </div>
            <!-- 左侧图片 (20%) -->
            <div class="newsImage">
              <img src="../assets/image/logo.jpg" alt="新闻图片" class="image" />
            </div>

            <!-- 右侧内容 (80%) -->
            <div class="newsContent">
              <h3 class="title">{{ item.title }}</h3>
              <p class="summary">{{ item.summary }}</p>
              <div class="meta">
                <span class="date">{{ item.date }}</span>
                <p></p>
                <span class="views">浏览: {{ item.viewCount }}次</span>
                <el-tag size="medium" :type="getTagType(item.category)">
                {{ getCategoryName(item.category) }}
                </el-tag>

                <el-tag 
                    v-if="item.isHot" 
                    size="medium" 
                    type="danger" 
                    class="hot-tag"
                    >
                    热门
                </el-tag>
              </div>
            </div>

          </div>
        </div>
      </div>
      <!-- 第四部分：页脚分页 -->
      <div class="footerPagination">
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :pager-count="5"
          layout="prev, pager, next, jumper"
          :jumper-text="'跳转'"
          prev-text="上一页"
          next-text="下一页"
          @current-change="handlePageChange"
        />
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus' 

const searchText = ref('') // 必须要有v-model绑定的变量
const router = useRouter()
const currentPage = ref(1) // 当前页码
const pageSize = ref(10) // 每页条数
const total = ref(100) // 总数据量

const hoveredCardId = ref(null) // 新增：记录当前悬停卡片的id
// 新增的响应式变量
const selectedNews = ref(new Set()) // 使用Set存储选中的新闻ID
const isBatchMode = ref(false) // 是否处于批量模式
const sortDirection = ref('desc') // 'asc' 或 'desc'
const currentCategory = ref(null) // 当前选中的分类（null表示全部）

// 分类选择处理
const handleCategorySelect = (index) => {
  currentCategory.value = Number(index)
  currentPage.value = 1
}




// 时间排序方法
const handleSortByTime = () => {
  // 切换排序方向
  sortDirection.value = sortDirection.value === 'desc' ? 'asc' : 'desc'
  
  // 创建新数组避免原地排序
  const sorted = [...newsList.value].sort((a, b) => {
    const dateA = new Date(a.date.replace(/-/g, '/')) // 兼容Safari
    const dateB = new Date(b.date.replace(/-/g, '/'))
    return sortDirection.value === 'desc' ? dateB - dateA : dateA - dateB
  })
  
  newsList.value = sorted
  currentPage.value = 1
  
  ElMessage.success(`已按时间${sortDirection.value === 'desc' ? '降序' : '升序'}排序`)
}







// 日期范围选择器的值
const dateRange = ref([])
// 是否启用日期筛选
const isDateFilterActive = ref(false)
// 存储筛选后的日期范围
const activeDateRange = ref({ start: null, end: null })

// 处理日期筛选
const handlefliterbyDateRange = () => {
  if (!dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择完整的日期范围')
    return
  }

  isDateFilterActive.value = true
  activeDateRange.value = {
    start: dateRange.value[0],
    end: dateRange.value[1]
  }
  
  currentPage.value = 1
  ElMessage.success(`已筛选 ${dateRange.value[0]} 至 ${dateRange.value[1]} 的新闻`)
}

// 重置日期筛选
const resetDateFilter = () => {
  isDateFilterActive.value = false
  activeDateRange.value = { start: null, end: null }
  dateRange.value = []
  currentPage.value = 1
  ElMessage.info('已取消日期筛选')
}


// 监听页码变化
watch(currentPage, (newVal, oldVal) => {
  if (newVal !== oldVal) {
    smoothScrollToTop()
  }
})

// 平滑滚动到顶部
const smoothScrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth', // 关键参数
  })
}

// 获取分类名称
const getCategoryName = (category) => {
  const map = { 1: '武大咨询', 2: '珞珈人物', 3: '信息发布', 4: '校园生活' }
  return map[category] || '未知分类'
}

// 获取标签类型
const getTagType = (category) => {
  const types = ['', 'success', 'warning', 'danger'] // 索引1-3对应类型
  return types[category-1] || ''
}
// 生成100条新闻数据
const newsList = ref(
  Array.from({ length: 100 }, (_, i) => ({
    id: i + 1,
    title: `武汉大学新闻标题 ${i + 1}`,
    date: `2025-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}-${String(Math.floor(Math.random() * 28) + 1).padStart(2, '0')}`,
    image: '../assets/image/logo.jpg',
    viewCount: Math.floor(Math.random() * 1000) + 100,
    category: Math.floor(Math.random() * 4) + 1 ,// 保持1-4的随机分类
    isHot: Math.random() > 0.7, // 30%的概率是热门新闻
    summary: `这是第 ${i + 1} 条新闻的摘要内容，这里是示例文本，可以根据实际需求替换真实内容...`,
  }))
)

// 添加筛选热门新闻的状态
const showHotNews = ref(false)

// 处理热门新闻筛选
const handleHotNews = () => {
  showHotNews.value = !showHotNews.value
  currentPage.value = 1
  ElMessage.success(showHotNews.value ? '已筛选热门新闻' : '已取消热门筛选')
}

// 计算当前页显示的数据
const paginatedNews = computed(() => {
  // 第一步：分类筛选
  let filteredNews = currentCategory.value
    ? newsList.value.filter(item => item.category === currentCategory.value)
    : [...newsList.value]
  
  // 第二步：热门筛选
  if (showHotNews.value) {
    filteredNews = filteredNews.filter(item => item.isHot)
  }
  
  // 第三步：日期筛选
  if (isDateFilterActive.value) {
    filteredNews = filteredNews.filter(item => {
      const newsDate = new Date(item.date.replace(/-/g, '/'))
      const startDate = new Date(activeDateRange.value.start.replace(/-/g, '/'))
      const endDate = new Date(activeDateRange.value.end.replace(/-/g, '/'))
      
      return newsDate >= startDate && newsDate <= endDate
    })
  }
  
  // 第四步：分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredNews.slice(start, end)
})

const handleSortByWatch = () => {
  newsList.value.sort((a, b) => b.viewCount - a.viewCount)
  currentPage.value = 1
  ElMessage.success('已按浏览量降序排序')
}

// 点击搜索跳转一个测试页面
const handleSearch = () => {
  if (searchText.value.trim()) {
    router.push({
      name: 'SearchResults', // 路由名称
      query: { q: searchText.value.trim() }, // 传递搜索关键词
    })
  } else {
    alert('请输入搜索内容') // 可选：空搜索提示
  }
}
</script>

<style scoped>
.date-filter-group {
  display: flex;
  align-items: center;
  margin-right: 0.625rem;
  vertical-align: middle; /* 确保与其他行内元素对齐 */
}

.date-range-picker {
  width: 17.5rem;
  margin: 0 0.625rem 0 0; /* 只保留右边距 */
  height: 2.5rem; /* 与按钮高度保持一致 */
}

.reset-date-filter {
  margin-left: 0.3125rem;
}

/* 使日期选择器和按钮在同一行对齐 */
.el-date-editor.el-input, .el-date-editor.el-input__inner {
  width: 100%;
}

/* 调整Element默认样式 */
.el-date-editor .el-range-separator {
  padding: 0 0.5rem; /* 调整分隔符间距 */
}

/* 中间内容区布局 */
.middle-content-area {
  display: flex;
  margin-top: 1.25rem;
}

/* 左侧分类栏 */
.category-sidebar {
  width: 20%;
  padding-right: 1.25rem;
}

.category-card {
  background: #fff;
  border-radius: 0.5rem;
  box-shadow: 0 0.125rem 0.75rem 0 rgba(0, 0, 0, 0.1);
  padding: 0.9375rem;
}

.category-title {
  font-size: 1.125rem;
  font-weight: bold;
  margin-bottom: 0.9375rem;
  color: #333;
}

.category-menu {
  border-right: none;
}

.category-item {
  font-size: 1rem;
  padding: 0.75rem 1.25rem !important;
  border-radius: 10%;
}

.el-menu-item.is-active {
  background-color: #f5f7fa;
  color: #409eff;
  font-weight: bold;
}
/* 右侧新闻内容区 */
.news-main-content {
  width: 80%;
}

/*

-----整体样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

 */

body {
  margin: 0;
  padding: 0;
}

:deep(.el-container) {
  padding: 0 !important;
  margin: 0 !important;
}

.el-main {
  padding: 0 0.625rem; /* 保留少量内边距 */
  max-width: 100%;
}

.banner-image img {
  display: block; /* 移除图片底部间隙 */
}

/*

-----header样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

 */

.topBar {
  height: 1.875rem;
  width: 100%;
  background-color: #b6daff;
}

/* 固定头部样式 */
.fixed-header {
  position: fixed !important;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000; /* 确保在最上层 */
  width: 100% !important;
}

/* 占位元素样式 (根据您实际的header高度调整) */
.header-placeholder {
  height: 8.125rem; /* topBar(1.875rem) + headerContent(6.25rem) */
}

/* 标题区域样式 */
.customHeader {
  background-color: #ffffff; /* 背景眼色 */
  color: rgb(7, 0, 0); /* 文字颜色 */
  padding: 0 1.25rem;
  height: 7.5rem;
  display: flex;
  align-items: center;
  flex-direction: column; /* 改为垂直布局 */

  transform: translateY(-0.125rem); /* 向上浮动一点点 */
  box-shadow:
    0 0.25rem 0.5rem rgba(0, 0, 0, 0.1),
    0 0.5rem 1rem rgba(0, 0, 0, 0.1),
    0 0.75rem 1.5rem rgba(0, 0, 0, 0.1); /* 多层叠加阴影，营造立体感 */
  position: relative; /* 确保阴影可见 */
  z-index: 1000; /* 保持悬浮层级 */
}


/* 标题内容样式 */
.headerContent {
  width: 100%;
  display: flex;
  justify-content: space-between; /* 改为左右布局 */
  align-items: center;
}

/* logo样式 */
.logo {
  height: 5rem;
  width: auto;
  object-fit: contain;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
}

.logo:hover {
  transform: translateY(-0.1875rem) scale(1.03);
  box-shadow: 0 0.625rem 1.25rem rgba(0, 0, 0, 0.1);
}

/* 标题容器 */
.titleWrapper {
  display: flex;
  flex-direction: column;
}

/* 主标题样式 */
.mainTitle {
  font-size: 2.5rem;
  font-weight: bold;
  color: #000;
}

/* News文字样式 */
.newsText {
  margin-left: 0.3125rem;
}

/* 副标题样式 */
.subTitle {
  font-size: 1.25rem;
  color: #409eff; /* Element Plus 主蓝色 */
}

/* 分割线 */
.headerDivider {
  height: 5rem;
  width: 0.0625rem;
  background-color: #c9d5f1;
}

/* 新增左侧容器 */
.headerLeft {
  display: flex;
  align-items: center;
  gap: 0.9375rem;
}

/* 右侧搜索框样式 */
.headerRight {
  width: 17.5rem;
  margin-left: auto;
}

/* 输入框样式 */
.searchInput {
  :deep(.el-input__inner) {
    height: 2.5rem;
    line-height: 2.5rem;
    font-size: 1rem;
    padding: 0 0.9375rem;
    /* 确保输入区域可点击 */
    pointer-events: auto;
    cursor: text;
  }

  :deep(.el-input__wrapper) {
    /* 移除可能遮挡的样式 */
    overflow: visible;
  }
}

.search-icon {
  width: 1.25rem;
  height: 1.25rem;
  object-fit: contain;
}

.headerRightGroup {
  display: flex;
  align-items: center;
  gap: 1.25rem;
}

/*

-----排序区域样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

 */

/* 添加热门按钮激活状态样式 */
.sortHot.is-active {
  background: var(--el-color-danger) !important;
  border-color: var(--el-color-danger) !important;
  color: white !important;
}

.sortTime {
  /* 添加过渡效果 */
  transition: all 0.3s ease;
  
  /* 当前激活状态 */
  &.active {
    background-color: var(--el-color-primary-light-9);
    border-color: var(--el-color-primary);
  }
}
 
/* 排序按钮区域样式 */
.sortButtons {
  display: flex;
  flex-wrap: wrap;
  align-items: center; /* 垂直居中 */
  gap: 0.3125rem;
  margin-bottom: 1.25rem;
}

/* "排序："文字样式 */
.sortLabelone {
  font-size: 1.125rem;
  color: #606266;
  margin-top: 1.875rem;
  margin-right: 0.625rem; /* 文字和按钮间距 */
  margin-bottom: 0rem;
  white-space: nowrap; /* 防止文字换行 */
}

/* "按日期筛选："文字样式 */
.sortLabel {
  font-size: 1rem;
  color: #606266;
  margin: 0.3125rem;
  white-space: nowrap; /* 防止文字换行 */
}

/* 统一的基础按钮样式 */
.sortBtn,
.sortBtnbyDateRange {
  display: inline-flex; /* 使用inline-flex保持行内特性 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  height: 2.5rem; /* 固定高度 */
  padding: 0 1.25rem; /* 左右内边距 */
  margin: 0rem 0.625rem 0 0; /* 只保留右边距 */
  font-size: 1rem; /* 统一字号 */
  line-height: 1; /* 重置行高 */
  border-radius: 0.25rem; /* 圆角统一 */
  background: white !important;
  border: 0.0625rem solid #dcdfe6 !important;
  color: #606266 !important;
  transition: all 0.3s ease;
  white-space: nowrap; /* 防止文字换行 */
}

/* 悬停状态 */
.sortBtn:hover,
.sortBtnbyDateRange:hover {
  background: #409eff !important;
  border-color: #409eff !important;
  color: white !important;
}

/* 特定按钮的微调 */
.sortBtnbyDateRange {
  margin-left: 0.625rem; /* 适当缩小左边距 */
}

/* 可选：按钮激活状态样式（点击后保持蓝色） */
.sortBtn.is-active {
  background: #409eff !important;
  border-color: #409eff !important;
  color: white !important;
}

/*

-----新闻卡片样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

 */

.date {
    font-size: 1.125rem;
}

.views {
    font-size: 0.8125rem;
}

.batch-controls {
    margin-left: 20%;
}

/* 新闻卡片样式 */


.newsContainer {
  width: 90%;
  margin: 0 auto;
  padding: 1.25rem;
}

.newsCard {
  margin-bottom: 1.25rem; /* 增加卡片间距 */
  transition: all 0.3s; /* 添加悬停动画 */
  display: flex;
  width: 100%;
  border: 0.0625rem solid #ebeef5;
  border-radius: 0.25rem;
  overflow: hidden;
  background: #fff;
  position: relative;
}

.newsCard:hover {
  box-shadow: 0 0.125rem 0.75rem rgba(0, 0, 0, 0.1);
  transform: translateY(-0.1875rem);
}

.newsImage {
  flex: 0 0 7.5rem; /* 固定宽度 */
  padding: 0.625rem;
  display: flex;
  align-items: center;
}

.image {
  width: 100%;
  height: 5rem; /* 固定高度 */
  object-fit: cover; /* 保持图片比例 */
}

.newsImage {
  flex: 0 0 20%;
}

.image {
  width: 70%;
  height: auto;
  object-fit: contain; /* 保持比例 */
}

.newsContent {
  flex: 0 0 80%;
  padding: 0.9375rem;
}

.title {
  font-size: 1.125rem;
  margin: 0 0 0.625rem 0;
  color: #303133;
}

.summary {
  font-size: 0.875rem;
  color: #606266;
  line-height: 1.6;
  margin: 0 0 0.625rem 0;
}

/* 日期区域 */
.meta {
  font-size: 0.75rem;
  color: #909399;
}

/*

-----页脚样式-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
 */

.footerPagination {
  position: fixed;
  bottom: 1.25rem;
  left: 0;
  right: 0;
  background: #fff;
  padding: 0.9375rem 0;
  display: flex;
  justify-content: center;
  box-shadow: 0 -0.125rem 0.625rem rgba(0, 0, 0, 0.1);
  z-index: 100;
}

.el-pagination {
  --el-pagination-font-size: 1.125rem !important;
}

.el-main {
  padding-bottom: 5rem !important; /* 等于或大于页脚高度 */
}
</style>
